
import React, { Component } from "react";
import {Route,Redirect} from 'react-router-dom';
import echo from './echo';
import request from "./request";
import action from "../../../store/action";

export function LocalParam (search, hash) {
    search = search || window.location.search;
    hash = hash || window.location.hash;
    var fn = function(str, reg) {
        if (str) {
            var data = {};
            str.replace(reg, function($0, $1, $2, $3) {
                data[$1] = $3;
            });
            return data;
        }
    };
    return {
        search : fn(search, new RegExp("([^?=&]+)(=([^&]*))?", "g")) || {},
        hash : fn(hash, new RegExp("([^#=&]+)(=([^&]*))?", "g")) || {}
    };
}
//router按需加载，自写
export  function AsyncComponent(importComponent) {
    class AsyncComponent extends Component {
        constructor(props) {
            super(props);
            this.state = {
                component: null
            };
        }
        async componentDidMount() {
            const {default:compoent} = await importComponent();
            this.setState({
                component: compoent
            });
        }
        render() {
            const C = this.state.component;
            return C ? <C {...this.props} /> : null;
        }
    }
    return AsyncComponent;
}
//不记录历史，进入页面
export function GoPageReplace(props,url){
    //replace不记录历史。push记录
    props.history.replace(window.base.config.path+url)
}
//记录历史，进入页面
export function GoPagePush(props,url){
    //replace不记录历史。push记录
    props.history.push(window.base.config.path+url)
}
//返回
export function  goBack(props) {
    props.history.goBack()
}
//reacr-router登录认证
export function AuthRoute({ component:Component, ...rest }) {
    return (
        <Route {...rest} render={props =>
            Boolean(localStorage['isLogin']) ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: window.base.config.path+"login/index",
                        state: { from: props.location }
                    }}
                />
            )
        }
        />
    );
}
//会员登录安全验证
export function safeAuto(props) {
    let sUrl=window.base.config.baseUrl+'home/user/safe?token='+window.base.config.token;
    request(sUrl,'post',{uid:props.state.redLogin.uid,auth_token:props.state.redLogin.authtoken}).then((res)=>{
        if (res.code!==200){
            props.dispatch(action.actLogin.actOutLogin({
                uid:'',
                username:'',
                authtoken:'',
                isLogin:false,
                success:()=>{
                    GoPagePush(props,'login/index')
                }
            }));
            props.dispatch(action.actCart.clearCart())
        }
    })

}
// 设置body向上滚动的高
export function setScrollTop(val=0) {
    // 移动端需要添加延迟
        //设置向上滚动的高
        document.body.scrollTop=val;
        document.documentElement.scrollTop=val;

}
//图片懒加载
export function lazyImg(){
    echo.init({
        offset : 100,//可是区域多少像素可以被加载
        throttle : 1 //设置图片延迟加载的时间
    });
}

//判断平台
export function isSystem(){
    let isWeixin=/micromessenger/i.test(navigator.userAgent);
    let isQQ=/QQ/i.test(navigator.userAgent);
    let isAndroid=/Android/i.test(navigator.userAgent);
    let isIphone=/iphone/i.test(navigator.userAgent);
    let isPCWindow=/window/i.test(navigator.userAgent);
    let isPCMac=/mac/i.test(navigator.userAgent);
    if(isWeixin){
        return 0;
    }
    else if(isIphone && !isQQ){
        return 1;
    }
    else if(isAndroid && !isQQ){
        return  2;
    }
    else if(isPCWindow){
        return 3;
    }
    else if(isPCMac && !isQQ){
        return 4;
    }else if(isQQ){
        return 5;
    }
}
//PC移动判断跳转
export function goSystem(props,url) {
    let temIsSystem=isSystem();
    let isflase = temIsSystem===3||temIsSystem===4;
    if (!isflase) {
        props.history.push(window.base.config.path+'mob/'+url)
    }else {
        props.history.push(window.base.config.path+url)
    }
}

//页面TDK
export function changeTdk(t,d,k){
    document.getElementById('title').innerHTML=t;
    document.getElementById('description').content=d;
    document.getElementById('keywords').content=k;
}